//
//  BBaseViewController.m
//  古诗词
//
//  Created by Rain on 2021/8/30.
//  Copyright © 2021 芥末. All rights reserved.
//

#import "BBaseViewController.h"
#import "SZFoldawayButton.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CommonCrypto/CommonDigest.h>
#import <net/if.h>
#import "SDHSportsNotchScreenUtil.h"

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"
//extern NSString *CTSettingCopyMyPhoneNumber();
@interface BBaseViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>{
    BOOL isLoad;
     NSInteger num;
        NSInteger count;
}
@property (weak, nonatomic)WKWebView *webView;
@property (nonatomic, strong) SZFoldawayButton *dzBtn;
@property (nonnull,copy) NSString *type;
@property (nonnull,copy) NSString *phoneStr;
@property(nonatomic ,strong)NSMutableArray *contantArr;
@end

@implementation BBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.contantArr = [NSMutableArray array];
    num = 0;
    count = 0;
    self.type = @"";
        self.phoneStr = @"";
    [self SetViews];
}
-(void)SetViews{
    // NSLog(@"-------------------%@",self.url);
    //! 为userContentController添加ScriptMessageHandler，并指明name
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addScriptMessageHandler:self name:@"ios_obj"];
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    CGFloat TabbarSafeBottomMargin = 0;
    if ([SDHSportsNotchScreenUtil isIPhoneNotchScreen]) {
        TabbarSafeBottomMargin = 34.f;
    }
    WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-TabbarSafeBottomMargin) configuration:configuration];
    [self.view addSubview: webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.bottom.right.equalTo(@0);
    }];
    webView.UIDelegate=self;
    webView.navigationDelegate = self;
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    [webView loadRequest:request];
    webView.navigationDelegate = self;
    self.webView = webView;
    SZFoldawayModel *model=[[SZFoldawayModel alloc]initWithmMainBtnTitle:nil selectTitle:nil image:@"cd_" selectImage:@"cd_"];
    model.subBtnImages = @[@"ht_", @"fx_", @"qc_", @"sy_", @"kf_",@"qj_",@"sx_"];
    model.subBtnSelectImages = @[@"ht_", @"fx_", @"qc_", @"sy_", @"kf_",@"qj_",@"sx_"];
    // 有弹簧效果 默认
    self.dzBtn = [[SZFoldawayButton alloc] initWithRect:CGRectMake(self.view.frame.size.width - 64, self.view.frame.size.width-150, 64, 64) andFoldAwayModel:model];
    self.dzBtn.showType = showTypeOfCircle;
    self.dzBtn.showSuperViewCenter = YES;
   [self.dzBtn showInView:self.view navigationBar:YES tabBar:YES];
    [self.dzBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@120);
        make.right.equalTo(@0);
        make.width.equalTo(@64);
        make.height.equalTo(@64);
    }];
    NSString *localip = [self getIPAddress];

              NSString *deviceUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
//              NSString *phone = CTSettingCopyMyPhoneNumber();
    __weak typeof(self) weakSelf = self;
    
    self.dzBtn.clickSubButtonBack = ^(int index, NSString *title, BOOL select){
        
        if (index==0) {//安全中心
                if ([weakSelf.safety_url containsString:@"http"]) {
            NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.safety_url]];
            [webView loadRequest:request];
                       }else{
                      [MBProgressHUD showError:@"web không hợp lệ"];
                                              }
          
        }
        if (index==1) {//分享
                 
                 //分享的标题
                 NSString *textToShare =weakSelf.shareTitle;
                 
                 NSArray *activityItems;
                 if ([weakSelf.shareTitle isEqualToString:@""]) {
                     activityItems = @[ textToShare];
                     
                 }else{
                     activityItems = @[textToShare];
                     
                 }
                 UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
                 //不出现在活动项目
                 activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
                 [weakSelf presentViewController:activityVC animated:YES completion:nil];
                 // 分享之后的回调
                 activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                     if (completed) {
                         NSLog(@"completed");
                         //分享 成功
                     } else  {
                         NSLog(@"cancled");
                         //分享 取消
                     }
                 };
                 
             }

        if (index==2) {//缓存
            NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
            NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
            //NSLog ( @"cachpath = %@" , cachePath);
            for ( NSString * p in files) {
                
                NSError * error = nil ;
                //获取文件全路径
                NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
                
                if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
                    [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
                }
            }
//            [HHAlertView showWithTitle:@"Xóa bộ nhớ cache thành công"];
            [MBProgressHUD showError:@"Xóa bộ nhớ cache thành công"];
            
        }
     if (index==3) {//
          NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.url]];
                 [webView loadRequest:request];
     }
        if (index==4) {//客服
            NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.QQStr]];
                                    [webView loadRequest:request];
        }
        if (index==5) {//
                     if ([weakSelf.handsel_url containsString:@"http"]) {
               NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.handsel_url]];
               [webView loadRequest:request];
                          }else{
                         [MBProgressHUD showError:@"web không hợp lệ"];
                                                 }
            }
        if (index==6) {//
               if ([weakSelf.discount_url containsString:@"http"]) {
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.discount_url]];
        [webView loadRequest:request];
                   }else{
                  [MBProgressHUD showError:@"web không hợp lệ"];
                                          }
            
        }
        
        if (index == 1 || index == 4) {
            UIViewController *vc = [[UIViewController alloc] init];
            vc.view.backgroundColor = [UIColor whiteColor];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else {
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
    
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
 
    isLoad = YES;
    if (num == 0) {
        num = 1;
    }
    NSString *WV = [NSString stringWithFormat:@"%@",webView.URL];
    if (self.download_url == nil || self.download_url.length == 0) {

    }else{
    NSArray *arr = [self.download_url componentsSeparatedByString:@":"];
    if ([WV containsString:arr[1]]) {

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.download_url]];
    }else{

    }
    }
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // NSLog(@"网页导航加载完毕");
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    isLoad = NO;
    //跳转到下载界面
    NSString *WV = [NSString stringWithFormat:@"%@",webView.URL];
    NSString *vb = [NSString stringWithFormat:@"%@/#/",self.url];
    if ([WV containsString:self.url]) {
    }else{
        self.type = @"qp";
        
    }
    if ([self.type isEqualToString:@"qp"]) {
        if ([WV isEqualToString:vb]) {
            if (count == 0) {
                [self.webView reload];
                count =1;
            }else{
                
                count =0;
            }
            
            
        }
    }
    
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

//-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
//{
//    //如果是跳转一个新页面
//    if (navigationAction.targetFrame == nil) {
//        [webView loadRequest:navigationAction.request];
//    }
//
//    decisionHandler(WKNavigationActionPolicyAllow);
//}


#pragma mark - WKScriptMessageHandler

//! WKWebView收到ScriptMessage时回调此方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([message.name caseInsensitiveCompare:@"ios_obj"] == NSOrderedSame) {
        
        //  NSLog(@"123455");
        [self goback];
    }
}
-(void)goback{
    //[self.webView goBack];
    
    UIViewController *BaseTabbar = [[UIViewController alloc] init];
    AppDelegate *appDelegate =(AppDelegate *)[[UIApplication sharedApplication]delegate];
    appDelegate.window.rootViewController.definesPresentationContext = YES;
    appDelegate.window.rootViewController = BaseTabbar;
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"ios_obj"];
}
- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}
- (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}
-(NSString *)md5:(NSString *)str
{
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    
    return digest;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
